package com.tantou.leetcode.easy;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

/**
 * @author jiangweiyang
 * @created 2020/4/30 11:41
 **/
public class SingleNumber {

    /**
     * https://leetcode-cn.com/problems/single-number/solution/cou-yi-pian-ti-jie-hua-shuo-ti-jie-hen-hao-wan-by-/
     * @param args
     */
    public static void main(String[] args){
        int[] nums = new int[]{1,3,2,2,3};
        System.out.println(single(nums));
        System.out.println(xor(nums));
    }

    /**
     * 异或
     */
    public static int xor(int[] nums){
        int ret = 0;
        for(int i=0;i<nums.length;i++){
            ret^=nums[i];
        }
        return ret;
    }
    /**
     * hash 额外存储空间
     */
    public static Integer single(int[] nums){
        Set<Integer> set = new HashSet<Integer>();
        for(int i=0;i<nums.length;i++){
            if(!set.contains(nums[i])){
                set.add(nums[i]);
            }else{
                set.remove(nums[i]);
            }
        }
        Iterator<Integer> iterator = set.iterator();
        while(iterator.hasNext()){
            return iterator.next();
        }
        return null;
    }
}
